import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from xuanba_model.models import Users
from xuanba_setting.settings import SECRET_KEY


class UserAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                result = jwt.decode(token, SECRET_KEY, algorithm='HS256')
                user = Users.objects.get(user_id=result['data']['user_id'])
                return user, token
            except Exception:
                pass
        raise AuthenticationFailed('请提供有效的身份认证标识')


class AllowGetAuthentication(BaseAuthentication):

    def authenticate(self, request):
        if request.method == 'GET':
            return None, None


class AllowPostAuthentication(BaseAuthentication):

    def authenticate(self, request):
        if request.method == 'POST':
            return None, None